package com.ios.controller;

import com.ios.model.entity.Room;
import com.ios.model.entity.Seat;
import com.ios.service.RoomService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/room")
public class RoomController extends BaseController {

    @Autowired
    private RoomService roomService;

    /**
     * 查询自习室列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Room room) {
        startPage();
        List<Room> list = roomService.selectRoomList(room);
        return getDataTable(list);
    }

    /**
     * 获取自习室详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(roomService.selectRoomById(id));
    }

    /**
     * 新增自习室
     */
    @PostMapping
    public AjaxResult add(@RequestBody Room room) {
        return roomService.insertRoom(room);
    }

    /**
     * 修改自习室
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Room room) {
        return roomService.updateRoom(room);
    }

    /**
     * 删除自习室
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 检查是否有座位关联
        for (Long id : ids) {
            int seatCount = roomService.countSeatsByRoomId(id);
            if (seatCount > 0) {
                return error("删除失败，自习室ID " + id + " 下还有 " + seatCount + " 个座位，请先删除相关座位");
            }
        }
        return toAjax(roomService.deleteRoomByIds(ids));
    }

    /**
     * 上传封面
     */
    @PostMapping("/uploadCover")
    public AjaxResult uploadCover(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return error("上传文件不能为空");
            }
            // 验证文件类型
            String contentType = file.getContentType();
            if (!contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            // 文件大小限制 (1MB)
            if (file.getSize() > 1048576) {
                return error("文件大小不能超过1MB");
            }

            // 创建D盘的upload目录（如果不存在）
            String uploadDir = "D:/upload/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs(); // 创建多级目录
            }

            // 存储文件到D:/upload/
            String fileName = UUID.randomUUID() + "." + StringUtils.getFilenameExtension(file.getOriginalFilename());
            String filePath = uploadDir + fileName;
            file.transferTo(new File(filePath));

            // 返回完整访问URL
            String baseUrl = "http://localhost:8080";
            String accessUrl = baseUrl + "/profile/upload/" + fileName;

            return AjaxResult.success("上传成功")
                    .put("url", accessUrl);
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }
    /**
     * 查询自习室下的所有座位
     */
    @GetMapping("/{roomId}/seats")
    public TableDataInfo getSeatsByRoomId(@PathVariable Long roomId) {
        startPage();
        List<Seat> list = roomService.selectSeatsByRoomId(roomId);
        return getDataTable(list);
    }
}